package com.mediautils.audioutils;

import android.app.Notification;
import android.app.NotificationManager;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.media.MediaRecorder;
import android.os.Environment;
import android.os.Handler;
import android.os.IBinder;
import androidx.core.app.NotificationCompat;
import android.util.Log;

import com.fileutils.FileUtils;
import com.tools.R;
import com.utils.DateUtils;
import com.dialogutils.ToastUtil;

//import org.greenrobot.eventbus.EventBus;
import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Locale;
import java.util.Timer;
import java.util.TimerTask;

import static com.utils.DateUtils.DATE_FORMAT_14;

/**
 * Created by Daniel on 12/28/2014.
 */
public class MediaService extends Service{
    private static final String LOG_TAG = "RecordingService";
    private String mFileName = null;
    private String mFilePath = null;
    private MediaRecorder mRecorder = null;
    private long mStartingTimeMillis = 0;
    private long mElapsedMillis = 0;
    private int mElapsedSeconds = 0;
    private OnTimerChangedListener onTimerChangedListener = null;
    private static final SimpleDateFormat mTimerFormat = new SimpleDateFormat("mm:ss", Locale.getDefault());
    private Timer mTimer = null;
    private TimerTask mIncrementTimerTask = null;

    @Override
    public IBinder onBind(Intent intent){
        return null;
    }

    public interface OnTimerChangedListener{
        void onTimerChanged(int seconds);
    }

    @Override
    public void onCreate() {
        super.onCreate();
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        startRecording();
        return START_STICKY;
    }

    @Override
    public void onDestroy() {
        if (mRecorder != null) {
            stopRecording();
        }
        super.onDestroy();
    }

    public void startRecording(){
        if(createFileName()!=null&&!createFileName().equals("")){
            mFilePath = createFileName();
            mRecorder = new MediaRecorder();
            mRecorder.setAudioSource(MediaRecorder.AudioSource.MIC);
            mRecorder.setOutputFormat(MediaRecorder.OutputFormat.MPEG_4);
            mRecorder.setOutputFile(mFilePath);
            mRecorder.setAudioEncoder(MediaRecorder.AudioEncoder.AAC);
            mRecorder.setAudioChannels(1);
            try {
                mRecorder.prepare();
                mRecorder.start();
                mStartingTimeMillis = System.currentTimeMillis();
                //startTimer();
                //startForeground(1, createNotification());
            } catch (IOException e) {
                Log.e(LOG_TAG, "prepare() failed");
            }
            updateMicStatus();
        }else{
            ToastUtil.showShort(getBaseContext(),"文件创建失败");
        }
    }

    /**
     * 设置高质量音频录制
     */
    public void setPrefHighQuality(){
        mRecorder.setAudioSamplingRate(44100);
        mRecorder.setAudioEncodingBitRate(192000);
    }

    /**
     * 文件名生成
     *
     * @return
     */
    private String createFileName(){
        String output_Path = Environment.getExternalStorageDirectory().getAbsolutePath()+"/zj_audio";
        if(FileUtils.judeDirExists(new File(output_Path))){
            return output_Path+"/"+ DateUtils.getNowDateFormat(DATE_FORMAT_14)+".wav";
        }else{
           return null;
        }
    }

    private final Handler mHandler = new Handler();
    private Runnable mUpdateMicStatusTimer = new Runnable() {
        public void run() {
            updateMicStatus();
        }
    };

    /**
     * 获取音频分贝
     */
    private int BASE = 1;
    private int SPACE = 100;// 间隔取样时间

    private void updateMicStatus() {
        if (mRecorder != null) {
            double ratio = (double) mRecorder.getMaxAmplitude() / BASE;
            double db = 0;// 分贝
            if (ratio > 1)
                db = 20 * Math.log10(ratio);
            //EventBus.getDefault().post(new DBEvent((int) db));
            mHandler.postDelayed(mUpdateMicStatusTimer, SPACE);
        }
    }

    public void stopRecording(){
        //设置后不会崩
        mRecorder.setOnErrorListener(null);
        mRecorder.setPreviewDisplay(null);
        try {
            mRecorder.stop();
        } catch (IllegalStateException e) {
            Log.w("Yixia", "stopRecord", e);
        } catch (RuntimeException e) {
            Log.w("Yixia", "stopRecord", e);
        } catch (Exception e) {
            Log.w("Yixia", "stopRecord", e);
        }

        mElapsedMillis = (System.currentTimeMillis() - mStartingTimeMillis);
        mRecorder.release();

        /**
         * 将文件路径发送到主线程
         */
        //EventBus.getDefault().post(new AudioPathEvent(mFilePath));

        //Toast.makeText(getBaseContext(), "文件保存至：" + mFilePath, Toast.LENGTH_LONG).show();
        if (mIncrementTimerTask != null) {
            mIncrementTimerTask.cancel();
            mIncrementTimerTask = null;
        }
        mRecorder = null;
    }

    private void startTimer() {
        mTimer = new Timer();
        mIncrementTimerTask = new TimerTask() {
            @Override
            public void run() {
                mElapsedSeconds++;
                if (onTimerChangedListener != null)
                    onTimerChangedListener.onTimerChanged(mElapsedSeconds);
                NotificationManager mgr = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
                mgr.notify(1, createNotification());
            }
        };
        mTimer.scheduleAtFixedRate(mIncrementTimerTask, 1000, 1000);
    }

    //TODO:
    private Notification createNotification() {
        NotificationCompat.Builder mBuilder =
                new NotificationCompat.Builder(getApplicationContext())
                        .setSmallIcon(R.drawable.ic_mic_white_36dp)
                        .setContentTitle(getString(R.string.notification_recording))
                        .setContentText(mTimerFormat.format(mElapsedSeconds * 1000))
                        .setOngoing(true);

//        mBuilder.setContentIntent(PendingIntent.getActivities(getApplicationContext(), 0,
//                new Intent[]{new Intent(getApplicationContext(), RecordActivity.class)}, 0));
        return mBuilder.build();
    }
}
